import pymysql
from pymysql import Error
import time


def create_connection():
    """创建数据库连接，带重试机制和超时设置"""
    max_retries = 3
    retry_delay = 2  # 秒
    
    for attempt in range(max_retries):
        try:
            connection = pymysql.connect(
                host='127.0.0.1',      # 数据库主机地址
                user='root',  # 数据库用户名
                port=3306,  #数据库服务器端口
                password='root',  # 数据库密码
                database='gdcs',  # 数据库名称
                charset='utf8mb4',     # 字符编码
                cursorclass=pymysql.cursors.DictCursor,  # 返回字典格式的结果
                connect_timeout=30,    # 连接超时30秒
                read_timeout=60,       # 读取超时60秒
                write_timeout=60       # 写入超时60秒
            )
            
            # 测试连接是否有效
            with connection.cursor() as cursor:
                cursor.execute("SELECT 1")
            
            print(f"数据库连接成功 (尝试 {attempt + 1})")
            return connection
            
        except Error as e:
            print(f"数据库连接失败 (尝试 {attempt + 1}/{max_retries}): {str(e)}")
            if attempt < max_retries - 1:
                print(f"等待 {retry_delay} 秒后重试...")
                time.sleep(retry_delay)
                retry_delay *= 2  # 指数退避
            else:
                print("数据库连接重试次数已用完")
                return None